package cz.swosh.stomp.ejbtest;

import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 *
 * @author swosh
 */
@Stateless(name="XMLWriter")
@Remote(XMLWriterRemote.class)
@Local(XMLWriter.class)
public class XMLWriterBean implements XMLWriterRemote, XMLWriter {


    @Override
    public Document writeMarkers(List<Person> pl){
        Document doc = null;
        try {
            DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
            doc = docBuilder.newDocument();
            doc.setXmlVersion("1.1");
            Element root = doc.createElement("markers");
            doc.appendChild(root);

            for (Iterator<Person> it = pl.iterator(); it.hasNext();) {
                Person person = it.next();
                Element marker = doc.createElement("marker");
                root.appendChild(marker);
                Element id = doc.createElement("id");
                id.setTextContent(String.valueOf(person.getId()));
                Element name = doc.createElement("name");
                name.setTextContent(person.getName());
                Element lat = doc.createElement("lat");
                lat.setTextContent(Double.toString(person.getLat()));
                Element lon = doc.createElement("lon");
                lon.setTextContent(Double.toString(person.getLon()));
                marker.appendChild(id);
                marker.appendChild(lat);
                marker.appendChild(lon);
                marker.appendChild(name);
            }




        } catch (ParserConfigurationException ex) {
            Logger.getLogger(XMLWriter.class.getName()).log(Level.SEVERE, null, ex);
            return doc;
        }
        return doc;
    }
}
